/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CoreGUI.java
 *
 * Created on Mar 3, 2009, 10:05:47 PM
 */

package com.wisc.csvParser;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import org.apache.log4j.Logger;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;




/**
 *
 * @author lawinslow
 */
public class CoreGUI extends JFrame implements PropertyChangeListener {

    private ZiggyStardust ziggystardust;
    private static Logger logger = Logger.getLogger("CoreGUI");

    /** Creates new form CoreGUI */
    public CoreGUI(ZiggyStardust c) {
        initComponents();
        this.ziggystardust = c;
        this.setSize(new Dimension(640,492));
        this.setupCloseListener();
        c.addPropertyChangeListener(this);

    }

    private void setupCloseListener(){
        this.setDefaultCloseOperation ( JFrame. DO_NOTHING_ON_CLOSE );
        WindowListener windowListener = new WindowAdapter()
           {
            @Override
           public void windowClosing ( WindowEvent w )
              {
                //hide this form.
                setVisible(false);
                dispose();
                ziggystardust.saveAndClose();
              }
           };

        this.addWindowListener( windowListener );

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        chainsTabbedPane = new javax.swing.JTabbedPane();
        addChainButton = new javax.swing.JButton();
        removeChainButton = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        loadMenuItem = new javax.swing.JMenuItem();
        saveMenuItem = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        settingsMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        addChainButton.setText("Add Chain");
        addChainButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addChainButtonActionPerformed(evt);
            }
        });

        removeChainButton.setText("Remove Chain");
        removeChainButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeChainButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(addChainButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(removeChainButton)
                .addContainerGap(334, Short.MAX_VALUE))
            .addComponent(chainsTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 532, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addChainButton)
                    .addComponent(removeChainButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chainsTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE))
        );

        fileMenu.setText("File");

        loadMenuItem.setText("Load Chains...");
        loadMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(loadMenuItem);

        saveMenuItem.setText("Save Chains...");
        saveMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(saveMenuItem);

        jMenuItem1.setText("Exit");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemExitActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem1);

        jMenuBar1.add(fileMenu);

        editMenu.setText("Edit");

        settingsMenuItem.setText("Settings");
        settingsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                settingsMenuItemActionPerformed(evt);
            }
        });
        editMenu.add(settingsMenuItem);

        jMenuBar1.add(editMenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


    private void addChainButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addChainButtonActionPerformed

        //logger.trace("Adding new chain");
        IDataParser testParser;
        IDataRepository repo;
        ParserPickerDialog parserPicker = new ParserPickerDialog(this,true);
        parserPicker.setLocationRelativeTo(this);
        RepositoryPickerDialog repoPicker = new RepositoryPickerDialog(this,true);
        repoPicker.setLocationRelativeTo(this);
        ChainNamerDialog namePicker = new ChainNamerDialog(this, true);
        namePicker.setLocationRelativeTo(this);


        try{

            parserPicker.setVisible(true);
            if(parserPicker.getReturnStatus() == ParserPickerDialog.RET_CANCEL)
                return;

            repoPicker.setVisible(true);
            if(repoPicker.getReturnStatus() == RepositoryPickerDialog.RET_CANCEL)
                return;


            namePicker.setVisible(true);


            testParser = DataParserFactory
                    .getParser(parserPicker.getReturnType());
            repo = DataRepositoryFactory
                    .getDataRepository(repoPicker.getReturnType());



            DataChain chain = new DataChain();
            chain.setFinalRepository(repo);
            chain.setSourceParser(testParser);
            chain.setChainName(namePicker.getName());

            //Add GUI component
            //DataChainJPanel tmp = new DataChainJPanel(chain);
            //chainsTabbedPane.add(chain.getChainName().toString(), tmp);
            
            //add chain to main app
            ziggystardust.addChain(chain);

        }catch(Exception e){

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw, true);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            logger.error("Error while adding chain.\n" + sw.toString());
        }
    }//GEN-LAST:event_addChainButtonActionPerformed

    private void saveMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveMenuItemActionPerformed
        FileDialog newConfig = new FileDialog(this);
        newConfig.setMode(FileDialog.SAVE);
        newConfig.setVisible(true);
        if(newConfig.getFile() == null){
            return;
        }

        ziggystardust.saveSettingsToFile(newConfig.getDirectory()+"/"+newConfig.getFile());
    }//GEN-LAST:event_saveMenuItemActionPerformed

    private void loadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadMenuItemActionPerformed
        FileDialog newConfig = new FileDialog(this);
        newConfig.setMode(FileDialog.LOAD);
        newConfig.setVisible(true);
        if(newConfig.getFile() == null){
            return;
        }
        ziggystardust.loadSettingsFromFile(newConfig.getDirectory()+"/"+newConfig.getFile());
    }//GEN-LAST:event_loadMenuItemActionPerformed

    private void settingsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_settingsMenuItemActionPerformed
        SettingsDialog d = new SettingsDialog(this,true);
        d.setLocationRelativeTo(this);
        d.setVisible(true);
    }//GEN-LAST:event_settingsMenuItemActionPerformed

    private void removeChainButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeChainButtonActionPerformed

        Component selected = chainsTabbedPane.getSelectedComponent();
        //if nothing selected, don't do anything
        if(selected == null)
            return;
        //if they don't confirm, don't do anything
        int pos = chainsTabbedPane.getSelectedIndex();
        String name = chainsTabbedPane.getTitleAt(pos)==null? "":chainsTabbedPane.getTitleAt(pos);

        if(JOptionPane.showConfirmDialog(this,
                "Are you sure you want to remove "+
                "the \""+name+"\" chain?")!=JOptionPane.OK_OPTION)
             return;

        //Remove the panel.
        chainsTabbedPane.remove(selected);
        //remove chain from main program object.
        ziggystardust.removeChain(((DataChainJPanel)selected).getDataChain());


    }//GEN-LAST:event_removeChainButtonActionPerformed

    private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExitActionPerformed
        ziggystardust.saveAndClose();
	}//GEN-LAST:event_jMenuItemExitActionPerformed

    @Override
    public void propertyChange(PropertyChangeEvent evnt){
        
        if(evnt.getPropertyName().equals("chainadded")){
            DataChain tmp = (DataChain)evnt.getNewValue();
            chainsTabbedPane.add(tmp.getChainName(),tmp.getJPanel());
        }else if(evnt.getPropertyName().equals("chainremoved")){
            DataChain tmp = (DataChain)evnt.getOldValue();
            chainsTabbedPane.remove(tmp.getJPanel());
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addChainButton;
    private javax.swing.JTabbedPane chainsTabbedPane;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JMenuItem loadMenuItem;
    private javax.swing.JButton removeChainButton;
    private javax.swing.JMenuItem saveMenuItem;
    private javax.swing.JMenuItem settingsMenuItem;
    // End of variables declaration//GEN-END:variables

    class ShutdownHook extends Thread {
		@Override
		public void run() {
			ziggystardust.saveAndClose();
		}
    }

}
